import axios from 'axios'
import Qs from 'qs'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor 拦截请求，通常用于权限管理
service.interceptors.request.use(function(config) {
  // Do something before request is sent
  if (localStorage.token) {
    config.headers.Authorization = localStorage.token || ''
  }
  // 参数转换为表单模式
  if (config.data) {
    config.data = Qs.stringify(config.data)
  }
  // 设置请求头
  config.headers.post = {
    'Content-Type': 'application/x-www-form-urlencoded' // 模拟form表单方式提交请求
  }
  // config.headers.put = {
  //   'Content-Type': 'multipart/form-data' // 模拟form表单方式提交请求
  // }
  return config
}, function(error) {
  // Do something with request error
  return Promise.reject(error)
})

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */

  res => {
    console.log(res)
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
